/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    // 分治、树的递归
    TreeNode* Convert(TreeNode* p) {
        if(!p) return nullptr;
        if(!p->left && !p->right) return p;
        TreeNode* left = Convert(p->left);
        TreeNode* ans = left;
        while(left && left->right) left=left->right;
        if(left) {
            p->left = left;
            left->right = p;
        }
        TreeNode* right = Convert(p->right);
        if(right) {
            right->left = p;
            p->right = right;
        }
        return ans ? ans : p;
    }
};